#include "includes.h"
#include <termios.h>

static int rs485_fd;

static int uart_init(char *name, int speed)
{
	int fd;
	struct termios stOpt;
	fd = Open(name, O_RDWR|O_NOCTTY);//O_NDELAY
	tcgetattr(fd, &stOpt);
	tcflush(fd, TCIOFLUSH);
	
	//boud 
	cfsetispeed(&stOpt, speed);
	cfsetospeed(&stOpt, speed);

	//8n1
	stOpt.c_cflag &= ~CSIZE;
	stOpt.c_cflag |= CS8;
	stOpt.c_cflag &= ~CSTOPB;	
	stOpt.c_cflag &= ~PARENB;
	stOpt.c_cflag &= ~CRTSCTS;
	stOpt.c_iflag &= ~INPCK;

	//row data
	stOpt.c_cflag |= (CLOCAL | CREAD);
	stOpt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	stOpt.c_iflag &= ~(ICRNL | INLCR |IXON | IXOFF | IXANY | ISTRIP);
	stOpt.c_oflag &= ~OPOST;
	stOpt.c_cc[VTIME] = 1; 
	stOpt.c_cc[VMIN] = 0;
	
	if (tcsetattr(fd, TCSANOW, &stOpt) != 0)
	{
		err_sys("%s tcsetattr error", name);
	}
	tcflush(fd, TCIOFLUSH);
	return fd;
}



int uart_dev_init()
{
	rs485_fd = uart_init("/dev/ttyS2", B38400);
	return 0;
}




int uart_rs485_read(char *buf, int len)
{
	return Readn(rs485_fd, buf, len);
}

void uart_rs485_write(char *buf, int len)
{
	Writen(rs485_fd, buf, len);
}

int uart_rs485_read_timeout(char *buf, int len, int timeout)
{
	struct timeval time_value;
	fd_set fds;
	int ret;
	int cnt = 0;
	time_value.tv_sec = timeout;
	time_value.tv_usec = 0;
	
	
	FD_ZERO(&fds);
	FD_SET(rs485_fd, &fds);
	ret = Select(rs485_fd+1, &fds, NULL, NULL, &time_value);
	if (ret == 0)
	{
		//err_msg("the cmd time out: %s ", cmd);
		return -1;
	}
	if (FD_ISSET(rs485_fd, &fds))
	{
		cnt = uart_rs485_read(buf, len);
	}
	return cnt;
	
}


void uart_rs485_close()
{
	close(rs485_fd);
}
